package designpattern.responsibility;

import java.lang.reflect.Method;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ResiponsibilityHandlerAspect {

    protected final Log logger = LogFactory.getLog(getClass());

    @After("execution(* handlerRequest(..))")
    @SuppressWarnings({"unchecked"})
    private void checkResiponsibility(JoinPoint joinPoint) {
        try {
            Request request = (Request) joinPoint.getArgs()[0];
            Class<Handler> classType = joinPoint.getSignature().getDeclaringType();
            Method getSuccessor = classType.getMethod("getSuccessor", new Class[] {});
            Handler successor = (Handler) getSuccessor.invoke(joinPoint.getThis(), new Object[] {});

            Method getDeal = classType.getMethod("getDeal", new Class[] {});
            HashMap<Request, Boolean> deal = (HashMap<Request, Boolean>) getDeal
                    .invoke(joinPoint.getThis(), new Object[] {});

            boolean isDeal;
            if (!deal.containsKey(request)) {
                isDeal = false;
            } else {
                isDeal = deal.get(request);
            }
            if (successor != null && !isDeal) {
                logger.info("传给继任者:" + successor.getName());
                successor.handlerRequest(request);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
